package com.qjd.girl.controller;

import com.qjd.girl.domain.Girl;
import com.qjd.girl.domain.Result;
import com.qjd.girl.expection.GirlExpection;
import com.qjd.girl.repository.GirlRepository;
import com.qjd.girl.service.GirlService;
import com.qjd.girl.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by qiangjindong
 * 2018-08-03 10:45
 */
@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    // GET 获取女生列表
    @GetMapping(value = "/girls")
    public List<Girl> girlList() {
        return girlRepository.findAll();
    }

    // POST 创建一个女生
    @PostMapping(value = "/girlAdd")
    public Result girlAdd(@Validated Girl girl, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
//            return null;
        }
        return ResultUtil.success(girlRepository.save(girl));
    }

    // GET 通过id查询一个女生
    @GetMapping(value = "/girls/{id}")
    public Girl girlFindOne(@PathVariable(value = "id") Integer id) {
        // return girlRepository.findOne(id); // <parent>2.0.0之前
        return  girlRepository.findById(id).get();
    }

    // PUT 通过id更新一个女生
    @PutMapping(value = "girls")
    public Girl girlUpdate(@RequestParam(value = "id") Integer id,
                           @RequestParam(value = "age") Integer age,
                           @RequestParam(value = "cupSize") String cupSize) {
        Girl girl = new Girl();
        girl.setId(id);
        girl.setAge(age);
        girl.setCupSize(cupSize);
        return girlRepository.save(girl);
    }

    @PutMapping("/updateGirlById")
    public Girl updateGirlById(Girl girl) {
        return girlRepository.save(girl);
    }

    // DELETE 通过id删除一个女生 只能用 @PathVariable 注解
    @DeleteMapping(value = "/girls/{id}")
    public void girlDelete(@PathVariable(value = "id") Integer id) {
        girlRepository.deleteById(id);
    }

    // 自定义查询方法
    @PostMapping("/findByAge")
    public List<Girl> findByAge(Integer age) {
        return girlRepository.findByAge(age);
    }

    @PostMapping("/insertTwo")
    public void insertTwo() {
        girlService.inertTwo();
    }

    @GetMapping("/girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws GirlExpection {
        girlService.getAge(id);
    }
}